#include <sstream>
#include <iostream>
#include "tcpclient.h"
using namespace std;

bool TcpClient::connect(const string& ipp)
{
	inetaddr.set(ipp.empty() ? "localhost:65535" : ipp.data());

	return reconnect();
}

bool TcpClient::reconnect(void)
{
	close();
	int32_t r = connector.connect(*this, inetaddr);

	if(0 == r)
	{
		cout << connectionInfo() << endl;
		return true;
	}
	return false;
}

bool TcpClient::tryReconnect(const int32_t times, const int32_t interval)
{
	for(int32_t i = 0; i < (unsigned)times; i++)
	{
		if(reconnect())		
		{
			return true;
		}
		cerr <<	strerror(errno) 
			 << inetaddr.get_host_addr() << ":"
			 << inetaddr.get_port_number() 
			 << i << "times"
			 << endl;
		fflush(stdout);
		sleep((unsigned)interval);
	}
	return false;
}

string TcpClient::connectionInfo(void)
{
	ACE_INET_Addr l;
	ACE_INET_Addr r;
	char buf[128] = {};

	if( get_local_addr(l) == -1)
	{
		printf("get_local_addr failed!\n");
	}
	if(get_remote_addr(r) == -1)
	{
		printf("get_remote_addr failed!\n");
	}

	string lip,rip;

	l.addr_to_string(buf, sizeof(buf));
	lip = buf;
	r.addr_to_string(buf, sizeof(buf));
	rip = buf;

	stringstream ss;

	ss << "connection: from "
	   << lip << ":" << l.get_port_number()
	   << " to "
	   << rip << ":" << r.get_port_number();

	return ss.str();
}

int32_t  TcpClient::sendString(const string& s, const int32_t flags)
{
	return (int)send_n(s.data(), s.length(), flags);
}
